import EasyTyper from 'easy-typer-js'
import { isRef, Ref } from 'vue'
class Typing {
  static easyTyperConfigObject = {
    output: '',
    isEnd: false,
    speed: 80,
    singleBack: false,
    sleep: 10,
    type: 'custom',
    backSpeed: 40,
    sentencePause: false
  }

  start(content: Ref<string>, waitSymbol: string): void {
    function textGet(): string {
      return (<Ref<string>>content).value
    }
    function textSet(newText: string) {
      content.value = newText
    }
    const initText = textGet()
    textSet('') // 初始化字符串
    new EasyTyper(
      Typing.easyTyperConfigObject,
      initText,
      (instance: EasyTyper) => {
        // 回调函数
        // 此回调一般用于获取新的数据然后循环输出
        // instance { 实例EasyTyper }
        setTimeout(() => {
          const text = textGet()
          if (text.indexOf(waitSymbol) == text.length - 1) {
            textSet(text.substring(0, text.length - 2))
          }
        }, 20)
      },
      (output: string, instance: EasyTyper) => {
        // 钩子函数
        // output { 当前帧的输出内容 }
        // instance { 实例EasyTyper }
        // 通过钩子函数动态更新dom元素
        textSet(`${output} ${waitSymbol}`)
      }
    )
  }
}
export default Typing
